package jmine.tec.utils.cripto.key.impl;

import java.security.KeyPair;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;

import org.apache.commons.logging.LogFactory;

import jmine.tec.utils.cripto.key.KeyPairHolder;
import jmine.tec.utils.cripto.key.store.KeyStoreReader;

/**
 * {@link KeyPairHolder} que procura o par de chaves a partir de um {@link KeyStoreReader}
 * 
 * @author takeshi
 */
public class KeyStoreKeyPairHolder implements KeyPairHolder {

    private String keyAlias;

    private KeyStoreReader keyStoreReader;

    /**
     * @return the keyAlias
     */
    public String getKeyAlias() {
        return keyAlias;
    }

    /**
     * @param keyAlias the keyAlias to set
     */
    public void setKeyAlias(String keyAlias) {
        this.keyAlias = keyAlias;
    }

    /**
     * @return the keyStoreReader
     */
    public KeyStoreReader getKeyStoreReader() {
        return keyStoreReader;
    }

    /**
     * @param keyStoreReader the keyStoreReader to set
     */
    public void setKeyStoreReader(KeyStoreReader keyStoreReader) {
        this.keyStoreReader = keyStoreReader;
    }

    /**
     * {@inheritDoc}
     */
    public KeyPair get() {
        try {
            PrivateKey privateKey = this.keyStoreReader.getPrivateKey(keyAlias);
            PublicKey publicKey = this.keyStoreReader.getPublicKey(keyAlias);
            return new KeyPair(publicKey, privateKey);
        } catch (UnrecoverableKeyException e) {
            LogFactory.getLog(getClass()).warn("Cannot read keystore", e);
        } catch (KeyStoreException e) {
            LogFactory.getLog(getClass()).warn("Cannot read keystore", e);
        } catch (NoSuchAlgorithmException e) {
            LogFactory.getLog(getClass()).warn("Cannot read keystore", e);
        }
        return null;
    }

}
